package org.lemon.db.tx;

import org.lemon.db.store.BlockId;
import org.lemon.db.store.Page;

/**
 * @since 2024-12-13 12:17
 */
public class SetIntRecord extends LogRecord{

    private int offset;
    private int value;
    private BlockId blockId;

    public SetIntRecord() {
    }

    public SetIntRecord(int txNum, int offset, int value, BlockId blockId) {
        super(txNum);
        this.offset = offset;
        this.value = value;
        this.blockId = blockId;
    }

    @Override
    RecordType op() {
        return RecordType.SETINT;
    }

    @Override
    protected void undo(Transaction tx) {
        tx.pin(blockId);
        tx.setInt(blockId,offset,value,false);
        tx.unPin(blockId);
    }

    @Override
    public String toString() {
        return String.format("<SETINT %d %d %d %d>", txNumber(), blockId.getBlkNum(),
            offset, value);
    }

    @Override
    protected byte[] encode() {
        Page p = Page.create(1024);
        int bpos = 8 + p.strLen(blockId.getFileName());
        int offsetPos = bpos + 8;
        int valPos = offsetPos + 4;
        int rec_len = valPos + 4;

        byte[] rec = new byte[rec_len];

        p = Page.create(rec);
        p.setInt(0, op().getCode());
        p.setInt(TX_OFFSET, txNumber());

        p.setString(8, blockId.getFileName());
        p.setLong(bpos, blockId.getBlkNum());
        p.setInt(offsetPos, offset);
        p.setInt(valPos, value);
        return rec;
    }

    @Override
    protected int decode(Page page) {
        int offset = super.decode(page);

        String fileName = page.getString(offset);
        offset = offset + page.strLen(fileName);
        long blkId = page.getLong(offset);
        this.blockId = new BlockId(fileName,blkId);
        offset += 8;
        this.offset = page.getInt(offset);
        offset += 4;
        this.value = page.getInt(offset);
        return offset;
    }
}
